#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define OVERFLOW -2
#define ERROR -1
typedef int Status;
typedef int ElemType;
typedef struct Node
{
    ElemType data;
    Node* next;
}Node, *Link;
typedef struct
{
    Link front;
    Link rear;
    int length;
}Queue;
Status InitQueue(Queue &Q)
{
    Q.front = (Link)malloc(sizeof(Node));
    if (!Q.front)
        exit(OVERFLOW);
    Q.front->next = NULL;
    Q.rear = Q.front;
    Q.length = 0;
    return OK;
}
Status DestroyQueue(Queue &Q)
{
    Link p = Q.front;
    while (p)
    {
        Link cur = p;
        p = p->next;
        free(cur);
    }
    return OK;
}
Status ClearQueue(Queue &Q)
{
    Link p = Q.front->next;
    while (p)
    {
        Link cur = p;
        p = p->next;
        free(cur);
    }
    Q.front->next = NULL;
    Q.rear = Q.front;
    Q.length = 0;
    return OK;
}
Status QueueEmpty(Queue Q)
{
    if (Q.front == Q.rear)
        return TRUE;
    return FALSE;
}
Status QueueLength(Queue Q)
{
    return Q.length;
}
Status GetHead(Queue Q, ElemType &e)
{
    if (!Q.length)
        return ERROR;
    e = Q.front->next->data;
    return OK;
}
Status EnQueue(Queue &Q, ElemType e)
{
    Link p = (Link)malloc(sizeof(Node));
    if (!p)
        exit(OVERFLOW);
    p->data = e;
    p->next = NULL;
    Q.rear->next = p;
    Q.rear = p;
    ++Q.length;
    return OK;
}
Status DeQueue(Queue &Q, ElemType &e)
{
    if (!Q.length)
        return ERROR;
    Link cur = Q.front->next;
    e = cur->data;
    Q.front->next = Q.front->next->next;
    free(cur);
    if (!Q.front->next)
        Q.rear = Q.front;
    --Q.length;
    return OK;
}
Status QueueTraverse(Queue Q, bool (*visit)(ElemType e))
{
    int len = Q.length;
    printf("total: %d\n", len);
    printf("队头<-队尾\n");
    Link p = Q.front->next;
    for (int i = 0; i < len; ++i)
    {
        if (!visit(p->data))
            return ERROR;
        p = p->next;
    }
    printf("\n");
    return OK;
}
bool visit(ElemType e)
{
    printf("%d ", e);
    return TRUE;
}
int main(void)
{
    Queue Q;
    InitQueue(Q);
    QueueTraverse(Q, visit);
    ElemType e = 8;
    EnQueue(Q, e);
    e = 6;
    EnQueue(Q, e);
    QueueTraverse(Q, visit);
    e = 3;
    DeQueue(Q, e);
    printf("e = %d\n", e);
    QueueTraverse(Q, visit);
    GetHead(Q, e);
    printf("e = %d\n", e);
    ClearQueue(Q);
    QueueTraverse(Q, visit);

    return 0;
}